package com.dzsw.thread;

/**
 * @author sunz
 * @version 1.0
 * @CreateTime 2021-04-20-11:42
 */
public class InterruptMain {

    public static void main(String[] args) throws Exception {
        test2();
    }

    public static void test1() throws Exception {
        Thread t = new MyThread();
        t.start();
        Thread.sleep(2 * 1000); // 暂停1毫秒
        t.interrupt(); // 中断t线程
        t.join(); // 等待t线程结束
        System.out.println("end");
    }

    public static void test2() throws Exception {
        ExThread exThread = new ExThread();
        exThread.start();
        Thread.sleep(2 * 1000);
        exThread.interrupt();
        exThread.join();
        System.out.println("end.");
    }

}

class MyThread extends Thread {

    @Override
    public void run() {
        int n = 0;
        while (!isInterrupted()) {
            System.out.println(n++ + " hello!");
        }
    }
}

class ExThread extends Thread {

    @Override
    public void run() {
        HelloThread helloThread = new HelloThread();
        helloThread.start();
        try {
            helloThread.join();
        } catch (InterruptedException e) {
        }
        helloThread.interrupt();
        System.out.println("interrupted!");
    }
}

class HelloThread extends Thread {

    @Override
    public void run() {
        int n = 0;
        boolean running = true;
        while (running) {
            System.out.println("Hello, " + n++);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                System.out.println("interrupted!sleep!");
//                break;
            }
            running = !isInterrupted();
            System.out.println("interrupted = " + running);
        }
    }
}
